<?php
namespace app\farm\model;

use AlibabaCloud\Client\AlibabaCloud;
use app\BaseModel;
use app\shop\model\FreightTemplate;
use Exception;
use think\facade\Db;

class Config extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_config';


    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2022-07-01 15:46
     */
    public function getAppBannerAttr($value,$data){

        if(!empty($value)){

            $value = explode(',',$value);
        }

        return $value;

    }
    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        if(empty($data)){

            $this->dataAdd($dis);

            $data = $this->where($dis)->find();

        }

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 14:12
     * @功能说明:获取运费
     */
    public function getSendPrice($distance,$uniacid){

        $config = $this->dataInfo(['uniacid'=>$uniacid]);

        $y_distance = $distance - $config['start_distance'];

        if($y_distance<0){

            return $config['start_price'];

        }else{

          //  return  round($config['start_price']+$y_distance/$config['renew_distance']*$config['renew_price'],2);
            return  0;
        }

    }


    /**
     * @param $address_id
     * @param $goods_list
     * @param int $type
     * @功能说明:计算运费
     * @author chenniang
     * @DataTime: 2022-08-08 17:35
     */
    public function getTotalSendPrice($address_id,$goods_list,$type=1){

        $address_model = new Address();

        $address = $address_model->dataInfo(['id'=>$address_id]);

        if(empty($address)){

            return $type==1?0:['code'=>500,'msg'=>'地址信息错误'];
        }

        $frist_price = $frist_id = $addprice = 0;

        if(!empty($goods_list)){

            foreach ($goods_list as &$goods_info){
                //获取
                $tmpl_data = $this->getSendTmp($goods_info['send_tmpl_id'],$address,$type);

                if((!empty($tmpl_data['code'])&&$tmpl_data['code']==500)||empty($tmpl_data)){

                    return $tmpl_data;
                }

                $tmpl = $tmpl_data['tmpl'];
                //找到首费最大的模版
                if($tmpl['start_price']>$frist_price){

                    $frist_price = $tmpl['start_price'];

                    $frist_id    = $tmpl['id'];
                }
                //获取有多少个模版
                if(empty($tmpl_arr[$tmpl['id']])){

                    $tmpl_arr[$tmpl['id']] = $tmpl;
                }

                $tmpl_unit = !empty($tmpl_arr[$tmpl['id']]['tmpl_unit'])?$tmpl_arr[$tmpl['id']]['tmpl_unit']:0;

                $unit = $tmpl_data['type']==1?$goods_info['goods_num']:$goods_info['total_weight'];
                //计算每个模版的重量或者件数
                $tmpl_arr[$tmpl['id']]['tmpl_unit'] = $tmpl_unit+$unit;

            }

            foreach ($tmpl_arr as $tmpl){

                if($tmpl['id']==$frist_id){
                    //1按件数 2按重量
                    $add_num = ($tmpl['tmpl_unit'] - $tmpl['start_num'])>0?$tmpl['tmpl_unit'] - $tmpl['start_num']:0;

                }else{

                    $add_num = $tmpl['tmpl_unit'];

                }

                $add_num = $tmpl['add_num']>0?ceil($add_num/$tmpl['add_num']):0;

                $price = $add_num*$tmpl['add_price'];

                $addprice += $price;

               // dump($addprice,$frist_price);exit;

            }

        }

       // dump($addprice,$frist_price);exit;
        return round($addprice+$frist_price,2);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-09 13:50
     * @功能说明:获取模版
     */
    public function getSendTmp($send_tmpl_id,$address,$type){

        $tmpl_model = new FreightTemplate();

        $tmpl = $tmpl_model->dataInfo(['id'=>$send_tmpl_id]);

        if(empty($tmpl)){

            return $type==1?0:['code'=>500,'msg'=>'商品未管理模版'];
        }

        if(!empty($tmpl['config'])){

            foreach ($tmpl['config'] as $value){

                if(in_array($address['province'],$value['province'])){

                    $tmpl['tmpl'] = $value;

                    return $tmpl;

                }

            }

            return $type==1?0:['code'=>500,'msg'=>'地址未在配送范围内'];

        }else{

            return $type==1?0:['code'=>500,'msg'=>'地址未在配送范围内'];

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-22 17:51
     * @功能说明:获取商品运费信息
     */
    public function getGoodsSendPrice($address_id,$goods_info,$type=1,$data=1){

        $tmpl_model = new FreightTemplate();

        $address_model = new Address();

        $tmpl = $tmpl_model->dataInfo(['id'=>$goods_info['send_tmpl_id']]);

        if(empty($tmpl)){

            return $type==1?0:['code'=>500,'msg'=>'商品未管理模版'];
        }

        $address = $address_model->dataInfo(['id'=>$address_id]);

        if(empty($address)){

            return $type==1?0:['code'=>500,'msg'=>'地址信息错误'];
        }

        if(!empty($tmpl['config'])){

            foreach ($tmpl['config'] as $value){

                if(in_array($address['province'],$value['province'])){
                    //1按件数 2按重量
                    $unit = $tmpl['type']==1?$goods_info['goods_num']:$goods_info['total_weight'];

                    $add_num = ($unit - $value['start_num'])>0?$unit - $value['start_num']:0;

                    $add_num = $value['add_num']>0?ceil($add_num/$value['add_num']):0;

                    $price = round($value['start_price']+$add_num*$value['add_price'],2);

                    if($data==1){

                        return $price;

                    }else{

                        return ['price'=>$price,'type'=>$tmpl['type']];

                    }

                }

            }

            return $type==1?0:['code'=>500,'msg'=>'地址未在配送范围内'];

        }else{

            return $type==1?0:['code'=>500,'msg'=>'地址未在配送范围内'];

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-25 10:58
     * @功能说明:获取天气情况，默认甘孜
     */
    public function getWeather($uniacid,$lat='30.04932',$lang='101.9625'){

        $config = $this->dataInfo(['uniacid'=>$uniacid]);

        $key = $lat.'-'.$lang;

        $weather = getCache($key,$this->_uniacid);

        if(empty($weather)){

            $url  = 'https://apis.map.qq.com/ws/geocoder/v1/?location='.$lat.','.$lang;

            $url  = $url.'&key='.$config['map_secret'];

            $location = longbingCurl($url,[]);

            $location = json_decode($location,true);

            if(!empty($location['result']['address_component'])){

                $location = $location['result']['address_component'];

                if(!empty($location['province'])){

                    $province = $location['province'];

                    $city     = $location['city'];

                    $county   = $location['district'];

                    $url = 'https://wis.qq.com/weather/common?source=pc&weather_type=observe|forecast_24h|air&province='.$province.'&city='.$city.'&county='.$county;

                    $weather = file_get_contents($url);

                    $weather = @json_decode($weather,true);

                    setCache($key,$weather,7200,$this->_uniacid);
                }

            }

        }

        return $weather;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-25 11:16
     * @功能说明:获取天气情况，默认甘孜
     */
    public function getPlaceWeather($province='四川',$city='甘孜'){

        $key = $province.'-'.$city;

        $weather = getCache($key,$this->_uniacid);

        if(empty($weather)){

            $url = 'https://wis.qq.com/weather/common?source=pc&province='.$province.'&city='.$city.'&weather_type=observe|forecast_24h';

            $weather = file_get_contents($url);

            $weather = @json_decode($weather,true);

            setCache($key,$weather,7200,$this->_uniacid);
        }

        return $weather;

    }






    /**
     * @param $str_phone
     * @param $uniacid
     * @功能说明:发送短信验证码
     * @author chenniang
     * @DataTime: 2022-03-14 10:43
     */
    public function sendSms($str_phone,$uniacid){

        $dis = [

            'uniacid' => $uniacid
        ];

        $config = $this->dataInfo($dis);

        $keyId = $config['short_id'];

        $keySecret = $config['short_secret'];

        $SignName = $config['short_sign'];

        $TemplateCode = $config['short_code'];

        if(empty($keyId)||empty($keySecret)||empty($TemplateCode)){

            return false;
        }

        $code = mt_rand(100000,999999);

        setCache($str_phone,$code,600,$uniacid);

        AlibabaCloud::accessKeyClient($keyId, $keySecret)->regionId('cn-hangzhou') // replace regionId as you need
        ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "default",
                        'PhoneNumbers' => $str_phone,
                        //必填项 签名(需要在阿里云短信服务后台申请)
                        'SignName' => $SignName,
                        //必填项 短信模板code (需要在阿里云短信服务后台申请)
                        'TemplateCode' => $TemplateCode,
                        //如果在短信中添加了${code} 变量则此项必填 要求为JSON格式
                        'TemplateParam' => "{'code':$code}",
                    ],
                ])
                ->request();


            return !empty($result)?$result->toArray():[];
        } catch(Exception $e)
        {}
    }




}